import cv2
import threading
import queue
from modules.pose_detector import PoseDetector
from modules.game_controller import GameController
from modules.video_stream import VideoStream
from utils.config_loader import cfg

class PoseGame:
    def __init__(self):
        self.stream = VideoStream()
        self.controller = GameController()
        self.detector = PoseDetector()
        self.frame_queue = queue.Queue(maxsize=1)
        self.result_queue = queue.Queue(maxsize=1)
        self.running = False

    def capture_thread(self):
        while self.running:
            frame = self.stream.get_frame()
            if frame is None:
                break
            if not self.frame_queue.full():
                self.frame_queue.put(frame)

    def detection_thread(self):
        while self.running:
            if not self.frame_queue.empty():
                frame = self.frame_queue.get()
                results = self.detector.find_pose(frame)
                if not self.result_queue.full():
                    self.result_queue.put((frame, results))

    def action_thread(self):
        while self.running:
            if not self.result_queue.empty():
                frame, results = self.result_queue.get()
                if results:
                    self.controller.check_and_execute(results)
                cv2.imshow("Pose Detection", frame)
                if cv2.waitKey(1) & 0xFF == 27:
                    self.running = False

    def run(self):
        self.running = True
        threads = [
            threading.Thread(target=self.capture_thread),
            threading.Thread(target=self.detection_thread),
            threading.Thread(target=self.action_thread)
        ]
        for t in threads:
            t.daemon = True
            t.start()

        for t in threads:
            t.join()

        self.stream.release()
        cv2.destroyAllWindows()

def main():
    game = PoseGame()
    game.run()

if __name__ == "__main__":
    main()